﻿// Copyright (c) 2007-2021 西安交通信息投资营运有限公司 版权所有
// 作者:吕艳阳

using DevExpress.Utils.Design;
using DevExpress.XtraBars.Navigation;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows.Forms;
using XCI.Core;
using XCI.Helper;

namespace XCI.Windows
{
    [System.ComponentModel.DesignerCategory("Code")]
    public class DetailsTabPane : TabPane
    {
        private LoadingMask loading;

        //已加载的Tab页
        private readonly Dictionary<string, int> loadedTabs = new Dictionary<string, int>();

        /// <summary>
        /// 获取或者设置要加载的数据的主键,如果同时指定Grid或者Tree则从Grid或者Tree中读取选中行主键,此参数将被忽略
        /// </summary>
        [Browsable(false)]
        public string RecordId { get; set; }

        /// <summary>
        /// 所属的Grid控件,Grid和Tree二选一
        /// </summary>
        [DefaultValue(null), Category("XCI"), Description("所属的Grid控件,Grid和Tree二选一")]
        [SmartTagProperty("所属Grid", "XCI", 1, SmartTagActionType.RefreshAfterExecute)]
        public GridControlPlus Grid { get; set; }

        /// <summary>
        /// 所属的Tree控件,Grid和Tree二选一
        /// </summary>
        [DefaultValue(null), Category("XCI"), Description("所属的Tree控件,Grid和Tree二选一")]
        [SmartTagProperty("所属Tree", "XCI", 2, SmartTagActionType.RefreshAfterExecute)]
        public TreeListPlus Tree { get; set; }

        /// <summary>
        /// 上一条按钮,指定后自动绑定事件
        /// </summary>
        [DefaultValue(null), Category("XCI"), Description("上一条按钮,指定后自动绑定事件")]
        [SmartTagProperty("上一条按钮", "XCI", 3, SmartTagActionType.RefreshAfterExecute)]
        public Control PrevButton { get; set; }

        /// <summary>
        /// 下一条按钮,指定后自动绑定事件
        /// </summary>
        [DefaultValue(null), Category("XCI"), Description("下一条按钮,指定后自动绑定事件")]
        [SmartTagProperty("下一条按钮", "XCI", 4, SmartTagActionType.RefreshAfterExecute)]
        public Control NextButton { get; set; }

        [Category("XCI"), Description("Loading面板容器")]
        public Control LoadingOwner { get; set; }

        /// <summary>
        /// 当前数据属性
        /// </summary>
        [Browsable(false)]
        public DetailsFormManagerCurrent Current { get; } = new DetailsFormManagerCurrent();

        [Category("XCI"), Description("数据绑定事件")]
        public event EventHandler<DetailsFormPaneBindingEventArgs> PageBinding;


        /// <summary>
        /// 读取当前行或者指定Id的数据并绑定到控件
        /// </summary>
        public async Task BindingModelAsync()
        {
            if (WinFormHelper.IsDesignMode()) return;
            if (PageBinding == null) return;

            Control owner = LoadingOwner ?? this.FindForm();
            if (loading == null) loading = new LoadingMask(owner);
            //设置当前选中的标签页
            Current.TabPageName = this.SelectedPage.Name;
            if (string.IsNullOrEmpty(Current.TabPageName)) return;

            if (loadedTabs.ContainsKey(Current.TabPageName)) return;
            loadedTabs[Current.TabPageName] = 1;

            Current.Grid = Grid;
            Current.Tree = Tree;
            //设置当前记录的主键、Model以及按钮状态
            if (Grid != null)
            {
                Current.Id = Grid.SelectedId;
                Current.Model = Grid.Selected;
                SetBtnStatus(!Grid.IsFirstFocus, !Grid.IsLastFocus);
            }
            else if (Tree != null)
            {
                Current.Id = Tree.SelectedId;
                Current.Model = Tree.Selected;
                SetBtnStatus(!Tree.IsFirstRow, !Tree.IsLastRow);
            }
            else
            {
                if (string.IsNullOrEmpty(RecordId)) throw new ArgumentException("请指定Id", nameof(RecordId));
                Current.Id = RecordId;
                Current.Model = null;
                SetBtnStatus(false, false);
            }


            var args = new DetailsFormPaneBindingEventArgs { Current = Current };
            PageBinding?.Invoke(this, args);
            if (args.Task == null) throw new ArgumentNullException(nameof(args.Task));
            await loading.ShowAsync(args.Task);
        }

        /// <summary>
        /// 读取Grid或者Tree上一行数据并绑定到控件
        /// </summary>
        public async Task MovePrevBindingModelAsync()
        {
            loadedTabs.Clear();
            if (Grid != null)
            {
                Grid.CurrentColumnView.MovePrev();
                await BindingModelAsync();
            }
            else if (Tree != null)
            {
                Tree.MovePrev();
                await BindingModelAsync();
            }
        }

        /// <summary>
        /// 读取Grid或者Tree下一行数据并绑定到控件
        /// </summary>
        public async Task MoveNextBindingModelAsync()
        {
            loadedTabs.Clear();
            if (Grid != null)
            {
                Grid.CurrentColumnView.MoveNext();
                await BindingModelAsync();
            }
            else if (Tree != null)
            {
                Tree.MoveNext();
                await BindingModelAsync();
            }
        }

        /// <summary>
        /// 设置上一条/下一条按钮有效状态
        /// </summary>
        /// <param name="prevButtonStatus">上一条有效状态</param>
        /// <param name="nextButtonStatus">下一条有效状态</param>
        private void SetBtnStatus(bool prevButtonStatus, bool nextButtonStatus)
        {
            if (PrevButton != null) PrevButton.Enabled = prevButtonStatus;
            if (NextButton != null) NextButton.Enabled = nextButtonStatus;
        }

        protected override void OnCreateControl()
        {
            base.OnCreateControl();
            if (PrevButton != null) PrevButton.Click += async (o, e) => await MovePrevBindingModelAsync();
            if (NextButton != null) NextButton.Click += async (o, e) => await MoveNextBindingModelAsync();
        }

        protected override async void OnSelectedPageChanged(INavigationPageBase oldPage, INavigationPageBase newPage)
        {
            await BindingModelAsync();
        }
    }

    public class DetailsFormPaneBindingEventArgs : EventArgs
    {
        public DetailsFormManagerCurrent Current { get; set; }
        public Func<Task> Task { get; set; }
    }

    /// <summary>
    /// 详情管理器当前数据
    /// </summary>
    public class DetailsFormManagerCurrent
    {
        /// <summary>
        /// 当前Tree控件
        /// </summary>
        public TreeListPlus Tree { get; set; }

        /// <summary>
        /// 当前Grid控件
        /// </summary>
        public GridControlPlus Grid { get; set; }

        /// <summary>
        /// 当前主键
        /// </summary>
        public string Id { get; set; }

        /// <summary>
        /// 当前Model对象
        /// </summary>
        public object Model { get; set; }

        /// <summary>
        /// 当前标签页名称
        /// </summary>
        public string TabPageName { get; set; }
    }
}